/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.framework.base.web;

import java.beans.PropertyEditorSupport;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.xw.util.AppConstant;

/**
 * The Class TimestampEditor.
 *
 * @author Xi Wei
 * @version 1.0
 * @since 1.0
 */
public class TimestampEditor extends PropertyEditorSupport {

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#getAsText()
	 */
	public String getAsText() {
		Timestamp value = (Timestamp) getValue();
		if (null == value) {
			return "";
		}
		SimpleDateFormat df = new SimpleDateFormat(AppConstant.DEFAULT_DATETIME_FORMAT);
		return df.format(value);
	}

	/* (non-Javadoc)
	 * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
	 */
	public void setAsText(String text) throws IllegalArgumentException {
		Timestamp value = null;
		if (null != text && !text.equals("")) {
			SimpleDateFormat df = new SimpleDateFormat(AppConstant.DEFAULT_DATETIME_FORMAT);
			
			Date dt = null;
			
			try {
				dt = df.parse(text);
			} catch (ParseException e1) {
				df = new SimpleDateFormat(AppConstant.DEFAULT_DATE_FORMAT);
				try {
					dt = df.parse(text);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			if(dt != null){
				value = new Timestamp(dt.getTime());
			}
			
		}
		setValue(value);
	}
}